using System;
using System.Net;
using ENodeMicro.Common.Helpers;

namespace ENodeMicro.Common
{
    public static class ConfigSettings
    {
        #region ENode
        /// <summary>
        /// 业务库连接字符串
        /// </summary>
        public static string BusinessConnectionString { get; set; }
        /// <summary>
        /// 框架库连接字符串
        /// </summary>
        public static string ENodeConnectionString { get; set; }

        /// <summary>
        /// NameServer Port
        /// </summary>
        public static int NameServerPort { get; private set;} = 10191;
        #endregion

        #region Consul
        
        /// <summary>
        /// Consul 地址
        /// </summary>
        public static string ConsulAddress { get; private set; }
        
        #endregion

        #region GRpc
        public static string GRpcHttpScheme { get; private set; } = "http";
        /// <summary>
        /// GRpc端口号
        /// </summary>
        public static int GRpcPort { get; private set; } = 7001;
        /// <summary>
        /// Http端口号
        /// </summary>
        public static int HttpPort { get; private set; } = 80;
        #endregion
        
        /// <summary>
        /// 本地IPv4地址
        /// </summary>
        public static IPAddress LocalIpv4 { get; private set; }
        static ConfigSettings()
        {
        }
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialize()
        {
            // Consul地址
            ConsulAddress = GetEnvironmentValue("CONSUL_ADDRESS","http://localhost:8500");
            GRpcHttpScheme = GetEnvironmentValue("GRPC_HTTP_SCHEME","http");
            LocalIpv4 = NetworkHelper.GetLocalIpv4();
            GRpcPort = NetworkHelper.FindNextAvailableTcpPort(10000);
            var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (env == "Development")
            {
                HttpPort = NetworkHelper.FindNextAvailableTcpPort(11000);
            }
        }

        /// <summary>
        /// 读取环境变量值
        /// </summary>
        /// <param name="envName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        private static string GetEnvironmentValue(string envName,string defaultValue="")
        {
            var envValue = Environment.GetEnvironmentVariable(envName);
            if (string.IsNullOrEmpty(envValue))
            {
                return defaultValue;
            }
            return envValue;
        }
    }
}